﻿var express=require('express');
var request=require('request');
var session=require('express-session');
var bodyParser = require('body-parser');
var fs=require('fs');

/**
 * @param appid id
 * @param appsec 密钥
 */

var appid="";
var appsec="";

/**
 * @param ucurl 鉴权服务器地址
 * @param proxyurl 第三方api服务器地址
 */
var ucurl="";
var proxyurl="";

var app=express();

var proxyreq={
    //重试次数
    i:0,
    //执行函数
    exe:function(req,res){
        var tmp=this;
        request({
            method:req.method,
            url:proxyurl+req.originalUrl,
            headers:{
                "content-type": "application/json",
                "Authorization":"Bearer "+req.session.access_token
            },
            body:JSON.stringify(req.body)
        },function(error,response,body){
            if (typeof(response)=="undefined")
            {
                res.status(500);
                res.send('后端服务器未返回任何报文,应该是老华的服务器炸了,这个错误是中间件抛出的');
                return;
            }

            if (!error && response.statusCode == 200) {
                res.status(response.statusCode);
                //没有type的时候默认类型为html
                if (typeof(response.headers['content-type'])=="undefined"){
                    response.headers['content-type']="text/html";
                    res.send(body);
                    return;
                }

                //json类型
                if (response.headers['content-type'].indexOf('application/json')!=-1)
                {
                    res.json(JSON.parse(body));
                    return;
                }
                //html类型
                if (response.headers['content-type'].indexOf('text/html')!=-1)
                {
                    res.send(body);
                    return;
                }
                //文件
                if (response.headers['content-type'].indexOf('application/ms-excel')!=-1)
                {
                    res.end();
                    return;
                }

                //文件
                if (response.headers['content-type'].indexOf('application/octet-stream')!=-1)
                {
                    var filename=decodeURI(response.headers['content-disposition'].substr(response.headers['content-disposition'].indexOf("filename=")+9));
                    var fileurl=__dirname+'\\file\\'+filename;
                    var stream = fs.createWriteStream(fileurl);
                    request({
                        url:proxyurl+req.originalUrl,
                        headers:{
                            "content-type": "application/json",
                            "Authorization":"Bearer "+req.session.access_token
                        }
                    }).pipe(stream).on("close",function(){
                        res.download(fileurl,filename);
                        return;
                    });
                    //这里必须return
                    return;
                }

                res.send(body);
                return;
            }
            else
            {
                switch(parseInt(response.statusCode))
                {
                    case 401:
                        tmp.flushtoken(req,res);
                        break;
                    default:
                        res.status(response.statusCode || 500);
                        res.send(body);
                        break;
                }
            }
        });


    },
    ////执行函数
    //刷token函数
    flushtoken:function(req,res){
        var tmp=this;
        
        if (typeof(req.session.refresh_token)=="undefined")
        {
            res.status(401);
            res.json({"Message":"no auth"});
            return;
        }

        request({
            method:"POST",
            url:ucurl+"/token",
            form:{
                grant_type:"refresh_token",
                refresh_token:req.session.refresh_token,
                client_id:appid,
                client_secret:appsec
            }
        },function(error, response, body){
            if (typeof(response)=="undefined")
            {
                res.status(500);
                res.send('后端服务器未返回任何报文,应该是老华的服务器炸了,这个错误是中间件抛出的');
                return;
            }

            if (!error && response.statusCode == 200) {
                req.session.access_token=JSON.parse(body).access_token;
                req.session.refresh_token=JSON.parse(body).refresh_token;
                tmp.exe(req,res);
            }
            else{
                res.status(response.statusCode);
                res.send(body);
                return;
            }
        });
        ////刷token函数

    }

}


app.use(express.static('public'));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// for parsing multipart/form-data

app.use(session({
    secret:"jinhe",
    name:"sid",
    resave:false,
    saveUninitialized:true
}));

app.listen(3000,function(){
    console.log('服务已启动,端口3000,项目是金禾OA办公系统');
});

app.get('/',function(req,res){
    res.sendFile(__dirname + '/public/index.html');
});

app.get('/m',function(req,res){
    res.sendFile(__dirname + '/public/index_mobile.html');
});

app.get('/wrong',function(req,res){
    res.sendFile(__dirname + '/public/wrong.html');
});

//路由表
var pages=['personManager','projectManager','jobLog','WorkCount'];

for (let i in pages)
{
    app.get('/'+pages[i],function(req,res){
        res.sendFile(__dirname + '/public/index.html');
    });

}

app.post('/login',function(req,res){

    request({
        method:"POST",
        url:ucurl+"/token",
        form:{
            grant_type:"password",
            username:req.body.username,
            password:req.body.password,
            client_id:appid,
            client_secret:appsec
        }
    },function(error, response, body){
        if (typeof(response)=="undefined")
        {
            res.status(500);
            res.send('后端服务器未返回任何报文,应该是老华的服务器炸了,这个错误是中间件抛出的');
            return;
        }
        
        if (!error && response.statusCode == 200) {
            req.session.access_token=JSON.parse(body).access_token;
            req.session.refresh_token=JSON.parse(body).refresh_token;
            //console.log('loginin');
            //console.log(req.session);
            res.json({"Message":"ok"});
            return;
        }
        else{
            res.status(response.statusCode);
            res.send(body);
            return;
        }
    });
});

app.post('/loginout',function(req,res){
    delete req.session.access_token;
    delete req.session.refresh_token;
    res.json({"Message":"ok"});
});

app.post('/loginoutacs',function(req,res){
    delete req.session.access_token;
    
    res.json({"Message":"ok"});
});

app.get('/islogin',function(req,res){
    if (req.session.access_token){
        res.send(true);
    }else{
        res.send(false);
    }
});

app.get('/gettoken',function(req,res){
    
    res.send(req.session.access_token);

});

app.all('/api/*',function(req,res){
    proxyreq.exe(req,res);
});

app.get('*', function(req, res){
    res.status(404)
    res.send('404 Not Found');
});
